<script setup>
import { ref, onMounted } from 'vue'
import { Search, Refresh, Edit, Delete, Plus } from '@element-plus/icons-vue'
import { getStuList, getStuById, addStu, updateStu, violationStu } from '@/api/stu'
import { getAllClazz } from '@/api/clazz'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单数据
const searchForm = ref({
  name: '',
  degree: '',
  clazzId: ''
})

// 班级列表数据
const clazzList = ref([])

// 学历选项
const degreeOptions = ref([
  { value: 1, label: '初中' },
  { value: 2, label: '高中' },
  { value: 3, label: '大专' },
  { value: 4, label: '本科' },
  { value: 5, label: '硕士' },
  { value: 6, label: '博士' }
])

// 学员列表数据
const stuList = ref([])

// 分页数据
const pageData = ref({
  page: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const studentFormRef = ref()
const studentForm = ref({
  name: '',
  no: '',
  gender: '',
  phone: '',
  idCard: '',
  isCollege: '',
  address: '',
  degree: '',
  graduationDate: '',
  clazzId: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  no: [
    { required: true, message: '请输入学号', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' }
  ],
  isCollege: [
    { required: true, message: '请选择是否院校学员', trigger: 'change' }
  ]
  // 最高学历和所属班级不是必填，移除相关验证规则
}

// 查询方法
const handleSearch = () => {
  pageData.value.page = 1
  getStudentList()
}

// 清空方法
const handleReset = () => {
  searchForm.value.name = ''
  searchForm.value.degree = ''
  searchForm.value.clazzId = ''
  pageData.value.page = 1
  getStudentList()
}

// 获取学员列表
const getStudentList = async () => {
  let params = {
    page: pageData.value.page,
    pageSize: pageData.value.pageSize
  }
  
  if (searchForm.value.name) {
    params.name = searchForm.value.name
  }
  if (searchForm.value.degree) {
    params.degree = searchForm.value.degree
  }
  if (searchForm.value.clazzId) {
    params.clazzId = searchForm.value.clazzId
  }
  
  try {
    const result = await getStuList(params)
    stuList.value = result.data.rows
    pageData.value.total = result.data.total
  } catch (error) {
    ElMessage.error('获取学员列表失败')
    console.error(error)
  }
}

// 获取班级列表
const getClazzList = async () => {
  try {
    const result = await getAllClazz()
    clazzList.value = result.data
  } catch (error) {
    ElMessage.error('获取班级列表失败')
    console.error(error)
  }
}

// 处理分页变化
const handleSizeChange = (val) => {
  pageData.value.pageSize = val
  pageData.value.page = 1
  getStudentList()
}

const handleCurrentChange = (val) => {
  pageData.value.page = val
  getStudentList()
}

// 格式化学历显示
const formatDegree = (degree) => {
  const degreeMap = {
    1: '初中',
    2: '高中',
    3: '大专',
    4: '本科',
    5: '硕士',
    6: '博士'
  }
  return degreeMap[degree] || '未知'
}

// 格式化性别显示
const formatGender = (gender) => {
  return gender === 1 ? '男' : '女'
}

// 添加学员
const handleAddStudent = () => {
  dialogVisible.value = true
  dialogTitle.value = '添加学员'
  // 重置表单
  studentForm.value = {
    name: '',
    no: '',
    gender: '',
    phone: '',
    idCard: '',
    isCollege: '',
    address: '',
    degree: '',
    graduationDate: '',
    clazzId: ''
  }
  // 重置表单验证
  if (studentFormRef.value) {
    studentFormRef.value.resetFields()
  }
}

// 编辑学员
const handleEditStudent = async (row) => {
  dialogVisible.value = true
  dialogTitle.value = '编辑学员'
  // 获取学员详情
  try {
    const result = await getStuById(row.id)
    studentForm.value = { ...result.data }
  } catch (error) {
    ElMessage.error('获取学员信息失败')
    console.error(error)
  }
}

// 保存学员
const saveStudent = async () => {
  try {
    // 表单验证
    await studentFormRef.value.validate()
    
    // 根据是否有ID判断是新增还是编辑
    if (studentForm.value.id) {
      // 编辑学员
      await updateStu(studentForm.value)
      ElMessage.success('编辑成功')
    } else {
      // 添加学员
      await addStu(studentForm.value)
      ElMessage.success('添加成功')
    }
    
    // 关闭对话框
    dialogVisible.value = false
    
    // 重新加载列表
    getStudentList()
  } catch (error) {
    console.error(error)
    ElMessage.error('操作失败')
  }
}

// 删除学员
const handleDeleteStudent = (row) => {
  ElMessageBox.confirm('确定要删除该学员吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 这里应该调用删除接口，但接口文档中没有提供
      ElMessage.success('删除成功')
      getStudentList()
    } catch (error) {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 违纪处理
const handleViolation = (row) => {
  ElMessageBox.prompt('请输入违纪扣分', '违纪处理', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^[1-9]\d*$/,
    inputErrorMessage: '扣分必须为正整数'
  }).then(async ({ value }) => {
    try {
      // 调用违纪处理接口
      await violationStu(row.id, value)
      ElMessage.success('违纪处理成功')
      // 重新加载列表以更新违纪次数和分数
      getStudentList()
    } catch (error) {
      ElMessage.error('违纪处理失败')
      console.error(error)
    }
  }).catch(() => {
    ElMessage.info('已取消违纪处理')
  })
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm('确定要删除选中的学员吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('批量删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 页面加载时获取数据
onMounted(() => {
  getStudentList()
  getClazzList()
})

// 对话框标题
const dialogTitle = ref('添加学员')
</script>

<template>
  <div class="student-management">
    <h1>学员管理</h1>
    <br>
    <br>
    <!-- 搜索区域 -->
    <el-form :model="searchForm" inline style="text-align: left;">
      <el-form-item label="姓名">
        <el-input 
          v-model="searchForm.name" 
          placeholder="请输入姓名" 
          clearable
        />
      </el-form-item>
      
      <el-form-item label="最高学历">
        <el-select 
          v-model="searchForm.degree" 
          placeholder="请选择最高学历" 
          clearable
        >
          <el-option
            v-for="item in degreeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="所属班级">
        <el-select 
          v-model="searchForm.clazzId" 
          placeholder="请选择所属班级" 
          clearable
        >
          <el-option
            v-for="item in clazzList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button 
          type="primary" 
          :icon="Search" 
          @click="handleSearch"
        >
          查询
        </el-button>
        <el-button 
          :icon="Refresh" 
          @click="handleReset"
        >
          清空
        </el-button>
      </el-form-item>
    </el-form>
    
    <!-- 新增和批量删除按钮 -->
    <div style="text-align: left; margin: 20px 0;">
      <el-button 
        type="primary" 
        :icon="Plus"
        @click="handleAddStudent"
      >
        添加学员
      </el-button>
      <el-button 
        type="danger" 
        :icon="Delete"
        @click="handleBatchDelete"
      >
        批量删除
      </el-button>
    </div>
    
    <!-- 学员列表 -->
    <el-table :data="stuList" border stripe style="width: 100%; margin-top: 20px;" :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }">
      <el-table-column type="selection" width="50" />
      <el-table-column prop="name" label="姓名" width="100" />
      <el-table-column prop="no" label="学号" width="120" />
      <el-table-column prop="clazzName" label="班级" width="180" />
      <el-table-column prop="gender" label="性别" width="80">
        <template #default="scope">
          {{ formatGender(scope.row.gender) }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" width="130" />
      <el-table-column prop="degree" label="最高学历" width="130">
        <template #default="scope">
          {{ formatDegree(scope.row.degree) }}
        </template>
      </el-table-column>
      <el-table-column prop="violationCount" label="违纪次数" width="130" />
      <el-table-column prop="violationScore" label="违纪扣分" width="130" />
      <el-table-column prop="updateTime" label="最后操作时间"  />
      <el-table-column label="操作" >
        <template #default="scope">
          <el-button 
            type="primary" 
            link 
            :icon="Edit" 
            @click="handleEditStudent(scope.row)"
          >
            编辑
          </el-button>
          <el-button 
            type="warning" 
            link 
            @click="handleViolation(scope.row)"
          >
            违纪
          </el-button>
          <el-button 
            type="danger" 
            link 
            :icon="Delete" 
            @click="handleDeleteStudent(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <el-pagination
      v-model:current-page="pageData.page"
      v-model:page-size="pageData.pageSize"
      :page-sizes="[5, 10, 20, 50]"
      :total="pageData.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 20px; justify-content: flex-start;"
    />
  </div>
  
  <!-- 添加/编辑学员对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px">
    <el-form 
      ref="studentFormRef" 
      :model="studentForm" 
      :rules="rules" 
      label-width="120px"
    >
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input 
              v-model="studentForm.name" 
              placeholder="请输入姓名"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学号" prop="no">
            <el-input 
              v-model="studentForm.no" 
              placeholder="请输入学号"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 第二行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select 
              v-model="studentForm.gender" 
              placeholder="请选择性别"
              style="width: 100%"
            >
              <el-option label="男" :value="1"></el-option>
              <el-option label="女" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input 
              v-model="studentForm.phone" 
              placeholder="请输入手机号"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 第三行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="身份证号" prop="idCard">
            <el-input 
              v-model="studentForm.idCard" 
              placeholder="请输入身份证号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否院校学员" prop="isCollege">
            <el-select 
              v-model="studentForm.isCollege" 
              placeholder="请选择是否院校学员"
              style="width: 100%"
            >
              <el-option label="是" :value="1"></el-option>
              <el-option label="否" :value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 第四行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系地址">
            <el-input 
              v-model="studentForm.address" 
              placeholder="请输入联系地址"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最高学历" prop="degree">
            <el-select 
              v-model="studentForm.degree" 
              placeholder="请选择最高学历"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item in degreeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 第五行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="毕业时间">
            <el-date-picker
              v-model="studentForm.graduationDate"
              type="date"
              placeholder="请选择毕业时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属班级" prop="clazzId">
            <el-select 
              v-model="studentForm.clazzId" 
              placeholder="请选择所属班级"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item in clazzList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveStudent">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.student-management {
  padding: 20px;
}
</style>